<?php

/**
 * PHP for SQL Server
 * ODBC驱动
 */

namespace wtfphp\libs;

class mssql {
    private $connection;

    function __construct($config) {
        $this->con($config);
    }

    function __destruct() {
        odbc_close($this->connection);
    }

    /**
     * 数据库连接
     * @param $config   array(host,database,user,pwd)
     */
    function con($config) {
        if (empty($config['driver'])) {
            $config['driver'] = '{SQL Server Native Client 10.0}';
        }
        $this->connection = odbc_connect("Driver={$config['driver']};Server={$config['host']};Database={$config['database']};", $config['user'], $config['pwd']);
        if ($this->connection === false) {
            return false;
        }
    }

    /**
     * 捕获错误
     */
    function error() {
        $errArr = array('code' => odbc_error($this->connection), 'msg' => odbc_errormsg($this->connection));
        if (empty($errArr['msg'])) {
            return null;
        }
        return $errArr;
    }

    /**
     * SQL执行
     * @param $sql      语句
     * @param $bind     参数绑定
     * @param $resType 1：select，2：insert，3：delete/update
     */
    function sql($sql, $bind = array(), $resType = 1) {
        //执行
        $stmt = odbc_prepare($this->connection, $sql);
        odbc_execute($stmt, $bind);
        //返回
        $ret = array();
        switch ($resType) {
            case 1:
                while ($tmp = odbc_fetch_array($stmt)) {
                    $ret[] = $tmp;
                }
                break;
            case 2:
                $func = __FUNCTION__;
                $ret = $this->$func("SELECT @@IDENTITY AS id");
                $ret = $ret[0]['id'];
                break;
            case 3:
                $ret = odbc_num_rows($stmt);
                break;
            default:
                return false;
                break;
        }
        odbc_free_result($stmt);
        return $ret;
    }

    /**
     * --------------------------------------------------
     * 事务
     * --------------------------------------------------
     */
    function transBegin() {
        return odbc_autocommit($this->connection, false);
    }

    function transCommit() {
        return odbc_commit($this->connection);
    }

    function transBack() {
        return odbc_rollback($this->connection);
    }
}